
package com.feib.soeasy.security.captcha;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.octo.captcha.service.CaptchaServiceException;


/**
 * @title (#)ImageCaptchaServlet.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/19 create by Jimmy Liu<br>
 */
public class ImageCaptchaServlet extends HttpServlet {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final long serialVersionUID = -4743858737437290371L;

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        genernateCaptchaImage(httpServletRequest, httpServletResponse);
    }

    /**
     * @param request
     * @param response
     */
    private void genernateCaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-store");  
        response.setHeader("Pragma", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
        ServletOutputStream out = null;
        try {  
            out = response.getOutputStream();  
            String captchaId = request.getSession(true).getId();  
            BufferedImage challenge = (BufferedImage)  CaptchaServiceSingleton.getInstance().getChallengeForID(captchaId, request.getLocale());  
            ImageIO.write(challenge, "jpg", out);  
            out.flush();  
        } 
        catch (CaptchaServiceException e) {  
            logger.error("驗證碼產生錯誤", e);
        }
        catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally { 

            try {
                if (null != out)
                    out.close();
            }
            catch (IOException e) {
            }  
        } 
    }

}
